package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.UserDao;
import com.ytjj.qmyx.admin.dao.UsersCouponRelationDao;
import com.ytjj.qmyx.admin.model.request.GtPushRequest;
import com.ytjj.qmyx.admin.model.request.UserAddRequest;
import com.ytjj.qmyx.admin.model.request.UserRequest;
import com.ytjj.qmyx.admin.model.response.UserInfosResponse;
import com.ytjj.qmyx.admin.service.UserService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.admin.utils.GtPushUtil;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersExpertMapper;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.TokenUsersQueryRequest;
import com.ytjj.qmyx.users.model.TokenUsersRequest;
import com.ytjj.qmyx.users.model.Users;
import com.ytjj.qmyx.users.model.UsersExpert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private UsersExpertMapper usersExpertMapper;

    @Resource
    private UsersCouponRelationDao usersCouponRelationDao;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private GtPushUtil gtPushUtil;

    @Resource
    private ChannelProductService channelProductService;

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private UsersClient usersClient;

    @Override
    public CommonPage<UserInfosResponse> selectList(UserRequest user) {
        PageHelper.startPage(user.getPageNum(),user.getPageSize());
        List<UserInfosResponse> dynamics = userDao.selectList(user);
        if (CollectionUtils.isEmpty(dynamics)) {
            return null;
        }  //是否限制展示供货价角色
        boolean isLimitRole = channelProductService.checkIsLimitRole();
        List<String> telList = dynamics.stream().filter(item -> item.getTel() != null).map(UserInfosResponse::getTel).collect(Collectors.toList());
        List<Orders> h5TokenList = null;
        if (!CollectionUtils.isEmpty(telList)) {
            h5TokenList = ordersDao.queryTokenByTel(telList);
        }
        List<UsersResponse> data = null;
        if (!CollectionUtils.isEmpty(h5TokenList)) {
            List<TokenUsersQueryRequest> collect = h5TokenList.stream().map(item -> {
                TokenUsersQueryRequest request = new TokenUsersQueryRequest();
                request.setToken(item.getH5Token());
                request.setTel(item.getUserPhone());
                return request;
            }).collect(Collectors.toList());
            TokenUsersRequest request = new TokenUsersRequest();
            request.setQueryRequests(collect);
            data = usersClient.getTokenUser(request).getData();
        }

        for (UserInfosResponse dynamic : dynamics) {
            String oldTel = Optional.ofNullable(dynamic.getTel()).orElse("");
            if (isLimitRole) {
                if (StringUtils.isNotBlank(dynamic.getTel())) {
                    String tel = dynamic.getTel().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
                    dynamic.setTel(tel);
                }

            }
            if(!CollectionUtils.isEmpty(data)) {
                Optional<UsersResponse> first = data.stream().filter(item -> item.getTel().equals(oldTel)).findFirst();
                if (first.isPresent()) {
                    dynamic.setScore(first.get().getScore() == null ? dynamic.getScore() : first.get().getScore());
                }
            }
        }
        return CommonPage.restPage(dynamics);
    }

    @Override
    public CommonPage<UserInfosResponse> virtualList(UserRequest user) {
        PageHelper.startPage(user.getPageNum(),user.getPageSize());
        List<UserInfosResponse> dynamics = userDao.virtualList(user);
        if (!CollectionUtils.isEmpty(dynamics)) {
            for (UserInfosResponse userInfosResponse : dynamics) {
                userInfosResponse.setCouponCount(usersCouponRelationDao.getCouponCount(userInfosResponse.getId()));
                Integer id = userInfosResponse.getId();
                String nickname = null == userInfosResponse.getNickname() ? "" : userInfosResponse.getNickname();
                userInfosResponse.setIdAndName(id + "-" + nickname);
            }
        }
        return CommonPage.restPage(dynamics);
    }

    @Override
    public int updateUserStatus(Integer id) {
        Users users = usersMapper.selectByPrimaryKey(id);
        if(users.getStatus() == SysConfigConstants.User_Status.STATUS_1){
            users.setStatus(SysConfigConstants.User_Status.STATUS_2);
        }else if(users.getStatus() == SysConfigConstants.User_Status.STATUS_2){
            users.setStatus(SysConfigConstants.User_Status.STATUS_1);
        }
        return usersMapper.updateByPrimaryKeySelective(users);
    }

    @Override
    public int addUsersExpert(UsersExpert usersExpert) {
        usersExpert.setCreateTime(new Date());
        return usersExpertMapper.insertSelective(usersExpert);
    }

    @Override
    public int addUser(UserAddRequest request) {
        UserInfosResponse userInfosResponse = userDao.getUsers(request.getTel());
        if (null != userInfosResponse){
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.USER_EXIST));
        } else {
            // 虚拟用户，自动生成账号
            String account = "ytjj-v-" + System.currentTimeMillis();
            request.setAccount(account);
            int idNum = userDao.addUser(request);
            if (idNum > 0) {
                request.setId(request.getId());
                return userDao.addUserInfo(request);
            }
        }
        return 0;
    }

    @Override
    public void gtPushByUsers(GtPushRequest gtPushRequest) {
        List<String> cids = new ArrayList<>();
        String skipUrl = "";
        String title = "";
        String content = "";
        Map<String,Object> param = new HashMap<>();
        param.put("url",skipUrl);
        param.put("title",title);
        param.put("content",content);
        IPushResult iPushResult = gtPushUtil.pushToList(cids,param);
        log.debug("群推返回信息："+ JSONObject.toJSONString(iPushResult));
    }

    @Override
    public List<UserInfosResponse> queryAllUserList() {
        List<UserInfosResponse> result = userDao.selectUserIdByAll();
        return result;
    }

    @Override
    public Users selectByUserId(Integer userId) {
        return usersMapper.selectByPrimaryKey(userId);
    }
}
